//
//  ILMusicPlayerManager.m
//  ILife
//
//  Created by lanou on 15/10/27.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILMusicPlayerManager.h"

@interface ILMusicPlayerManager ()
@property(nonatomic, strong)AVPlayer *avPlayer;
@end

@implementation ILMusicPlayerManager

-(instancetype)init
{
    self = [super init];
    if (self) {
        _avPlayer = [[AVPlayer alloc]init];
    }
    return self;
}

+ (instancetype)shareManager
{
    static ILMusicPlayerManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[ILMusicPlayerManager alloc]init];
    });
    return manager;
}


-(void)playMusicWithURL:(NSURL *)file
{
    
    _avPlayer = [AVPlayer playerWithURL:file];
//    [_avPlayer play];
    _isPlay = YES;
       
}


- (void)musicPlay
{
    [_avPlayer play];
    _isPlay = YES;

}

- (void)musicPause
{
    if(_avPlayer.rate != 0.0)
    {
        [_avPlayer pause];
        _isPlay = NO;
    }
}

// 播放/暂停
- (void)playAndPause
{
    // avPalyer的rate属性，当rate== 0.0的时候表示未播放状态，1.0为播放状态
    if(_avPlayer.rate == 0.0)
    {
        [_avPlayer play];
        _isPlay = YES;
    }else
    {
        [_avPlayer pause];
        _isPlay = NO;
    }
}
-(CGFloat)finishTime
{
    
    CMTime time = _avPlayer.currentItem.duration;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value / time.timescale;
}


-(CGFloat)currentTime
{
    CMTime time = _avPlayer.currentTime;
    if (time.timescale == 0) {
        return 0;
    }
    return (time.value / time.timescale);
}

- (void)jumpToNewTime:(CGFloat)time
{
    if (_isPlay == YES) {
        [_avPlayer pause];
        _isPlay = NO;
        [self.avPlayer seekToTime:CMTimeMakeWithSeconds(time, self.avPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
            [_avPlayer play];
            _isPlay = YES;
        }];
    }else
    {
        [self.avPlayer seekToTime:CMTimeMakeWithSeconds(time, self.avPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
            
        }];
    }
}
@end
